<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Model\LogLogin;
use App\Model\LogPassword;
use App\Model\LogSummary;
use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;


class LoginController extends Controller
{
    //


    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function register(Request $request)
    {
        $errMsg['user_name'] = '';
        $errMsg['email'] = '';
        $errMsg['code'] = '';
        $errMsg['password'] = '';
        if ($request->method() == "POST") {
            //检测邮箱
            $flag = true;
            $data = $request->post();
            if (strlen(($data['user_name'])) < 3 || strlen(($data['user_name'])) > 30) {
                $errMsg['user_name'] = "用户名的长度必须在3 ~ 30个之间！";
                $flag = false;
            }
            if (!isEmail($data['email'])) {
                $errMsg['email'] = "请填写正确的邮箱地址！";
                $flag = false;
            }

            $code = Redis::get("yzm:" . $data['email']);
            if ($code != $data['code']) {
                $errMsg['code'] = "验证码错误！";
                $flag = false;
            }

            if (strlen($data['password']) < 6) {
                $errMsg['password'] = "密码长度不得小于6位！";
                $flag = false;
            }

            $first = DB::table("users")->where("user_name", $data['user_name'])->first();
            if (!empty($first)) {
                $errMsg['user_name'] = "用户名已经存在！";
                $flag = false;
            }

            $first = DB::table("users")->where("email", $data['email'])->first();
            if (!empty($first)) {
                $errMsg['email'] = "邮箱已被注册过！";
                $flag = false;
            }

            $ip = $request->getClientIp();
            if ($flag) {
                $uid = User::create($data);
                LogLogin::add($uid, $ip);
                LogSummary::add();
                User::getInfo($uid);
                return redirect('home/index');
            }
        }

        return view("login/register", ['errMsg' => $errMsg]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login(Request $request)
    {
        $errMsg['user_name'] = '';
        $errMsg['password'] = '';
        if ($request->method() == "POST") {
            //检测邮箱
            $flag = true;
            $data = $request->post();

            $first = DB::table("users")->where("user_name", $data['user_name'])->orWhere("email", $data['user_name'])->first();
            if (empty($first)) {
                $errMsg['user_name'] = "用户名或者邮箱还没注册！";
                $flag = false;
            } else {
                if (Hash::check($first->password,$data['password'])) {
                    $errMsg['user_name'] = "账号或则密码错误！";
                    $flag = false;
                }

                if ($first->status == '-1') {
                    $errMsg['user_name'] = "账号已被冻结，如有疑问请联系客服";
                    $flag = false;
                }

                $uid = $first->uid;
                $ip = $request->getClientIp();
                if ($flag) {
                    LogLogin::add($uid, $ip);
                    LogSummary::add('login_num', 1);
                    User::getInfo($uid);
                    return redirect('/home/index');
                }
            }
        }

        return view("login/login", ['errMsg' => $errMsg]);
    }


    public function forgetPassword(Request $request)
    {
        $errMsg['email'] = '';
        $errMsg['code'] = '';
        $errMsg['password'] = '';
        if ($request->method() == "POST") {
            //检测邮箱
            $flag = true;
            $data = $request->post();

            if (!isEmail($data['email'])) {
                $errMsg['email'] = "请填写正确的邮箱地址！";
                $flag = false;
            }

            if (strlen($data['password']) < 6) {
                $errMsg['password'] = "密码长度不得小于6位！";
                $flag = false;
            }

            $first = DB::table("users")->where("email", $data['email'])->first();
            if (empty($first)) {
                $errMsg['email'] = "邮箱未注册！";
                $flag = false;
            } else {

                if ($first->status == '-1') {
                    $errMsg['email'] = "账号已被冻结，如有疑问请联系客服";
                    $flag = false;
                }

                $code = Redis::get("yzm:" . $data['email']);
                if ($code != $data['code']) {
                    $errMsg['code'] = "验证码错误！";
                    $flag = false;
                }

                $uid = $first->uid;
                $ip = $request->getClientIp();
                if ($flag) {
                    $new_password = Hash::make($data['password']);
                    $result = User::updatePassword($data, $new_password);
                    LogPassword::add($first->password,$new_password, $ip);
                    return redirect('/login');
                }
            }
        }

        return view("login/forgetPassword", ['errMsg' => $errMsg]);
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendEmailCode(Request $request)
    {
        $data = ['email' => $request->post('email'), 'user_name' => $request->post('user_name'), 'code' => mt_rand(100000, 999999)];
        Redis::set("yzm:" . $data['email'], $data['code']);
        Redis::expire("yzm:" . $data['email'], 60);
        $result = Mail::send('emails.register', ['data' => $data], function ($message) use ($data) {
            $to = $data['email'];
            $message->to($to)->subject('欢迎注册本网站，请尽快激活您的账号！');
        });
        if ($result) {
            return response()->json([
                'code' => '400',
                'msg' => $result
            ]);
        } else {
            return response()->json([
                'code' => '200',
                'msg' => "success"
            ]);
        }
    }
}
